package com.quanyan.club.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.quanyan.activity.entity.ActivityInfo;
import com.quanyan.activity.service.ActivityOpenService;
import com.quanyan.api.APIRequest;
import com.quanyan.api.APIResponse;
import com.quanyan.club.constants.ClubConstants;
import com.quanyan.club.entity.RespClubBaseInfo;
import com.quanyan.club.entity.db.*;
import com.quanyan.club.entity.vo.req.admin.*;
import com.quanyan.club.entity.vo.resp.RespClubActivity;
import com.quanyan.club.entity.vo.resp.RespClubInfo;
import com.quanyan.club.entity.vo.resp.RespClubMemberInfo;
import com.quanyan.club.entity.vo.resp.admin.*;
import com.quanyan.club.mapper.*;
import com.quanyan.club.service.*;
import com.quanyan.club.thread.BatchActivitySolrIndexThread;
import com.quanyan.club.thread.BatchClubSolrIndexThread;
import com.quanyan.club.thread.ClubSolrIndexThread;
import com.quanyan.club.util.ActivityUtils;
import com.quanyan.club.util.ClubNameUtils;
import com.quanyan.common.Plugin.Page;
import com.quanyan.common.Plugin.PageObj;
import com.quanyan.common.constants.Constants;
import com.quanyan.common.utils.CommonUtils;
import com.quanyan.common.utils.DateUtils;
import com.quanyan.common.utils.Limit;
import com.quanyan.common.utils.StringUtil;
import com.quanyan.common.vo.resp.RespCity;
import com.quanyan.common.vo.resp.RespDistrict;
import com.quanyan.orderpay.request.ReqOrderInfo;
import com.quanyan.orderpay.response.RespOrderInfo;
import com.quanyan.orderpay.response.mq.RefundNotifyMsg;
import com.quanyan.orderpay.service.OrderPayService;
import com.quanyan.place.client.PlaceClient;
import com.quanyan.place.entity.apiresp.RespPlaceLocation;
import com.quanyan.search.entity.vo.ActivityIndexInfo;
import com.quanyan.search.service.ActivitySearchService;
import com.quanyan.search.service.impl.ActivitySearchServiceImpl;
import com.quanyan.search.service.impl.ClubSearchServiceImpl;
import com.quanyan.statium.api.resp.RespGameOrder;
import com.quanyan.statium.service.StadiumOpenService;
import com.quanyan.user.response.RespUserInfoBase;
import com.quanyan.user.response.RespUserInfoDetail;
import com.quanyan.user.serviceFacade.UserServiceFacade;
import org.apache.commons.lang3.StringUtils;
import org.mybatis.spring.SqlSessionTemplate;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.annotation.PostConstruct;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.text.NumberFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * Created by zhuo.shi on 2016/8/19.
 *
 * 俱乐部后台管理服务类
 */
@Service
public class ClubAdminMgmServiceImpl  extends BaseServiceImpl implements ClubAdminMgmService{
    //2015-11-05
    private final long AA_SETTLEMENT_DEADLINE = 1478275200000l;
    private static Logger logger = LoggerFactory.getLogger(ClubAdminMgmService.class);

    @Autowired
    private UserServiceFacade userServiceFacade;
    @Autowired
    private TbClubMapper clubMapper;
    @Autowired
    private TbClubMemberMapper clubMemberMapper;
    @Autowired
    private ClubMemberMapper clubMember;
    @Autowired
    private ClubMemberService clubMemberService;
    @Autowired
    private TbClubSystemLogoMapper clubSystemLogoMapper;
    @Autowired
    private TbClubWithdrawalsRecordMapper clubWithdrawalsRecordMapper;
    @Autowired
    private SqlSessionTemplate sqlSessionTemplate;
    @Autowired
    private TbClubActivitySettlementMapper clubActivitySettlementMapper;
    @Autowired
    private ActivityOpenService activityOpenService;
    @Autowired
    private ActivitySupportService activitySupportService;
    @Autowired
    private TbClubOfflineAccountStreamMapper clubOfflineAccountStreamMapper;
    @Autowired
    private ClubAccountExtendMapper clubAccountExtendMapper;
    @Autowired
    private CppService cppService;
    @Autowired
    private OrderPayService orderPayService;
    @Autowired
    private TbClubWithdrawalsApplyMapper clubWithdrawalsApplyMapper;
    @Autowired
    private TbClubOnlineAccountMapper clubOnlineAccountMapper;
    @Autowired
    private TbClubOnlineAccountStreamMapper clubOnlineAccountStreamMapper;
    @Autowired
    private TbOrderMapper orderMapper;
    @Autowired
    private TbClubFinanceDailyReportMapper clubFinanceDailyReportMapper;
    @Autowired
    private ClubFinanceDailyReportMapper clubFinanceDailyMapper;
    @Autowired
    private TbAASettlementRefundDetailMapper aaSettlementRefundDetailMapper;
    @Autowired
    private StadiumOpenService stadiumOpenService;
    @Autowired
    private ClubTaskService clubTaskService;
    @Autowired
    private ClubActivityService  clubActivityService;
    @Autowired
    private TbClubMultimediaMapper clubMultimediaMapper;
    @Autowired
    private PlaceClient<RespPlaceLocation> placeClient;
    @Autowired
    private TbSignUserMapper signUserMapper;
    @Autowired
    private ClubActivityMapper clubActivityMapper;
    @Autowired
    private TbClubTaskClubEggStreamMapper clubTaskClubEggStreamMapper;
    @Autowired
    private SignUserMapper signUser;

    @Autowired
    private ClubActivityAdminMapper clubActivityAdminMapper;

    private SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd");
    @Autowired
    private ClubSearchServiceImpl clubSearchService;
    @Autowired
    private ActivitySearchService activitySearchService;
    @PostConstruct
    protected  void init(){
        clubSearchService = new ClubSearchServiceImpl(searchCloudUrl);
    }

    @Autowired
    ThreadPoolTaskExecutor executor;
    @Autowired
    private ClubIntegralService clubIntegralService;

    @Override
    public void reIndexClub(Integer clubId){
        if (clubId == null){
            return;
        }
        TbClub tbClub = clubMapper.selectByPrimaryKey(clubId);
        RespClubBaseInfo clubBaseInfo = this.convert2ClubBaseInfo(clubId);
        clubBaseInfo.setGoingActivityCount(activitySupportService.countActivityAfterWeek(clubId));
        clubBaseInfo.setStar(clubIntegralService.updateSearchClubStar(clubId));
        executor.submit(new ClubSolrIndexThread(clubBaseInfo, clubSearchService, false));
    }

    @Override
    public PageObj<List<RespClubInfo>> queryClubList(ReqClubQuery clubQuery) {
        int pageNo = clubQuery.getPageNo();
        int pageSize = clubQuery.getPageSize();

        TbClubExample example = new TbClubExample();
        TbClubExample.Criteria criteria = example.createCriteria();
        Integer clubId = clubQuery.getClubId();
        if (clubId != null){
            criteria.andIdEqualTo(clubId);
        }
        String clubName = clubQuery.getClubName();
        if (!StringUtil.isBlankOrNull(clubName)){
            criteria.andClubNameLike(clubName+"%");//在“俱乐部列表”的俱乐部名称搜索中加入关键词搜索的模糊查询
        }
        String placeName = clubQuery.getResidentPlaceName();
        if (!StringUtil.isBlankOrNull(placeName)){
            criteria.andResidentPlaceNameEqualTo(placeName);
        }
        Integer jointype = clubQuery.getJoinType();
        if (jointype != null){
            criteria.andJoinTypeEqualTo(jointype.byteValue());
        }
        Integer sportTypeId = clubQuery.getSportTypeId();
        if (sportTypeId != null){
            criteria.andClubTypeEqualTo(sportTypeId);
        }
        Integer cityId = clubQuery.getCityId();
        if (cityId != null){
            criteria.andCityIdEqualTo(cityId);
        }
        Integer districtId = clubQuery.getDistrictId();
        if (districtId != null){
            criteria.andDistrictIdEqualTo(districtId);
        }
        Integer state = clubQuery.getState();
        if (state != null){
            criteria.andIsDeleteEqualTo(state.byteValue());
        }
        String founder= clubQuery.getFounder();
        if(!StringUtil.isBlankOrNull(founder)){
            criteria.andFounderNicknameEqualTo(founder);//在“俱乐部列表”中俱乐部创建人搜索
        }
        Date startQueryTime=clubQuery.getStartQueryTime();
        if (startQueryTime != null){
            logger.warn("startQueryTime=" + sf.format(startQueryTime));
            criteria.andCreateTimeGreaterThanOrEqualTo(startQueryTime);
        }
        Date endQueryTime = getEndQueryTime(startQueryTime,clubQuery.getEndQueryTime());
        if (endQueryTime != null){
            logger.warn("endQueryTime=" + sf.format(endQueryTime));
            criteria.andCreateTimeLessThan(endQueryTime);
        }
        example.setLimit(Limit.buildLimit(pageNo, pageSize));
        example.setOrderByClause("id desc");
        int total = clubMapper.countByExample(example);
        List<TbClub> list = clubMapper.selectByExample(example);
        List<RespClubInfo> resultList = new ArrayList<>();
        if(CollectionUtils.isEmpty(list))
        {
            return PageObj.create(total, pageNo, pageSize, resultList);
        }
        for (TbClub tbClub : list){
            Integer tbClubId = tbClub.getId();
            Map<String,Object> paramMap = new HashMap<String,Object>();
            paramMap.put("clubId", tbClubId);
            if(startQueryTime !=null && endQueryTime != null) {
                paramMap.put("startQueryTime", startQueryTime);
                paramMap.put("endQueryTime", endQueryTime);
            }
            int activityCount = clubActivityAdminMapper.countActivityByClub(paramMap);
            int memberCount = clubMemberService.countClubMembers(tbClubId, true);
            RespClubInfo respClubInfo = this.convert2ClubInfo(tbClub);
            respClubInfo.setMemberCount(memberCount);
            respClubInfo.setActivityCount(activityCount);
            resultList.add(respClubInfo);
        }

        return PageObj.create(total, pageNo, pageSize, resultList);
    }

    @Override
    public RespClubDetails queryClubDetails(Date trendStartTime,Date trendEndTime) {
        TbClubExample example = new TbClubExample();
        List<TbClub> list = clubMapper.selectByExample(example);
        RespClubDetails respClubDetails = new RespClubDetails();
        for (TbClub tbClub : list) {
            Integer id=tbClub.getId();
            Integer clubType = tbClub.getClubType();
            TbClubMemberExample tbClubMemberExample = new TbClubMemberExample();
            tbClubMemberExample.createCriteria()
                    .andClubIdEqualTo(tbClub.getId())
                    .andIsDeleteEqualTo(Constants.IS_DELETE_FALSE);
            int memberCount = clubMemberMapper.countByExample(tbClubMemberExample);
            List<Integer> activityIds = clubTaskService.getCycleActivityIds(id, "taskDay");
            int activityCountDay = 0;
            if(null != activityIds && activityIds.size() > 0)
            {
                activityCountDay = activityIds.size();
            }
            TbSignUserExample tbSignUserExample = new TbSignUserExample();
            tbSignUserExample.createCriteria().andActivityIdEqualTo(
                    id).andIsCancelEqualTo(Constants.ZERO)
                    .andStatusEqualTo(Constants.IS_YES);
            int  signUpActivityPeople = signUserMapper.countByExample(tbSignUserExample);

            BigDecimal costIncome = null;
            TbClubOnlineAccountExample tbClubOnlineAccountExample = new TbClubOnlineAccountExample();
            tbClubOnlineAccountExample.createCriteria().
                    andClubIdEqualTo(tbClub.getId()).andIsDeleteEqualTo((byte) 0);

            List<TbClubOnlineAccount> tbClubOnlineAccounts =
                    clubOnlineAccountMapper.selectByExample(tbClubOnlineAccountExample);
            if(null != tbClubOnlineAccounts && tbClubOnlineAccounts.size() > 0) {
                costIncome = tbClubOnlineAccounts.get(0).getMoneyTotal();
            }
            String clubApprove = null;
            String approveTime = null;
            Date date=new Date();
            SimpleDateFormat matter=new SimpleDateFormat("yyyy/MM/dd");

            RespUserInfoBase  user = getUserInfoBase(id);
            if (user != null) {
                String realName = user.getRealName();
                if (StringUtil.isBlankOrNull(realName)) {
                    clubApprove = "否";
                    approveTime = null;
                }else {
                    clubApprove = "是";
                    approveTime =matter.format(date);
                }
            }
            List<List<Integer>> everyDayActivityIds = clubTaskService.getEveryDayActivityCount(id,trendStartTime,trendEndTime);
            List<Integer> everyDayActivityCountList = new ArrayList<Integer>();
            if(null != everyDayActivityIds && everyDayActivityIds.size() > 0) {
                int everyDayActivityCount = everyDayActivityIds.get(0).size();
                everyDayActivityCountList.add(everyDayActivityCount);
            }
            List<Integer>   everyDayActivityPeople =
                    signUser.getEveryDayActivityPeople(id,trendStartTime,trendEndTime);
            respClubDetails.setMemberCount(memberCount);
            respClubDetails.setActivityCountDay(activityCountDay);
            respClubDetails.setSignUpActivityPeople(signUpActivityPeople);
//            respClubDetails.setAddUpBirdEggTotal(addUpBirdEggTotal);
//            respClubDetails.setUseUpBirdEggTotal(useUpBirdEggTotal);
            respClubDetails.setCostIncome(costIncome);
            respClubDetails.setClubApprove(clubApprove);
            respClubDetails.setApproveTime(approveTime);
            respClubDetails.setEveryDayActivityPeople(everyDayActivityPeople);
            respClubDetails.setEveryDayActivityCountList(everyDayActivityCountList);
//            this.everydayDataCompare(memberCount,
//                    activityCountDay, signUpActivityPeople,addUpBirdEggTotal,useUpBirdEggTotal,
//                    tbClub);
        }
        return respClubDetails;
    }


    private  RespClubDetails everydayDataCompare(int nowMemberCount,int nowActivityCountDay,int nowSignUpActivityPeople,
                                              int nowAddUpBirdEggTotal,int nowUseUpBirdEggTotal,TbClub tbClub){
        try {
            RespClubDetails respClubDetails = new RespClubDetails();
            int beforeMemberCount = clubMember.countByBeforeTimeExample(tbClub.getId());
            NumberFormat nt = NumberFormat.getPercentInstance();
            nt.setMinimumFractionDigits(2);
            float memberCountPercent=((float)(nowMemberCount-beforeMemberCount))/(float)nowMemberCount;
            nt.format(memberCountPercent);
            respClubDetails.setMemberCountPercent(memberCountPercent);

            List<Integer> activityIds = clubTaskService.getCycleActivityIdsInTime(tbClub.getId(), "taskDay");
            int beforeActivityCount = 0;
            if(null != activityIds && activityIds.size() > 0)
            {
                beforeActivityCount = activityIds.size();
            }
            float activityCountPercent=((float)(nowActivityCountDay-beforeActivityCount))/(float)nowActivityCountDay;
            nt.format(activityCountPercent);
            respClubDetails.setActivityCountPercent(activityCountPercent);

            int beforeSignUpActivityPeople = signUser.countSignUpActivityPeople(tbClub.getId());
            float signUpActivityPeopleCountPercent=((float)(nowSignUpActivityPeople-beforeSignUpActivityPeople))/(float)nowSignUpActivityPeople;
            nt.format(signUpActivityPeopleCountPercent);
            respClubDetails.setSignUpActivityPeopleCountPercent(signUpActivityPeopleCountPercent);
            //List<TbClubTask> parametersList = clubTaskEggParameters.selectByConditionExample(tbClub.getClubType());
            int beforeAddUpBirdEggTotal = 0;
            int beforeUseUpBirdEggTotal = 0;
//            if(null != parametersList && parametersList.size() > 0) {
//            for (TbClubTask tbClubTask : parametersList) {
//                beforeAddUpBirdEggTotal += tbClubTask.getEggForClub();
//                beforeUseUpBirdEggTotal += tbClubTask.getEggForMem();
//            }
//        }
            float addUpBirdEggTotalPercent=((float)(nowAddUpBirdEggTotal-beforeAddUpBirdEggTotal))/(float)nowAddUpBirdEggTotal;
            nt.format(addUpBirdEggTotalPercent);
            respClubDetails.setAddUpBirdEggTotalPercent(addUpBirdEggTotalPercent);

            float useUpBirdEggTotalPercent=((float)(nowUseUpBirdEggTotal-beforeUseUpBirdEggTotal))/(float)nowUseUpBirdEggTotal;
            nt.format(useUpBirdEggTotalPercent);
            respClubDetails.setUseUpBirdEggTotalPercent(useUpBirdEggTotalPercent);
            return  respClubDetails;
        }catch (NullPointerException e){
            throw e;
        }
    }

    @Override
    public void loadActivityIndexAll()
    {
        ActivitySearchService activitySearchService = new ActivitySearchServiceImpl(searchCloudUrl);
        List<Integer> activityIds = clubActivityMapper.selectActivityIdByStatusRepaire();
        logger.warn("未结束活动个数：" + activityIds.size());
        List<RespClubActivity> respClubActivities =
                clubActivityService.batchQueryActivityList(activityIds);
        logger.warn("solr地址：" + searchCloudUrl);
        logger.warn("-----------------------开始删除--------------------------");
        //先删除
        long t2 = System.currentTimeMillis();
        //先删除
        APIResponse response = activitySearchService.deleteDocsActivityByIds(activityIds);
        if (!response.isRet()){
            logger.warn("删除活动"+ activityIds +"索引失败，"+ response.getErrmsg());
        }
        logger.warn("删除活动ll索引，花费：{}, {}", JSON.toJSON(response), System.currentTimeMillis()-t2);

        List<ActivityIndexInfo> indexInfoList = new ArrayList<>();
        for(RespClubActivity respClubActivity : respClubActivities){
            ActivityIndexInfo activityIndexInfo = new ActivityIndexInfo();
            activityIndexInfo.setActivity_placeAddress(respClubActivity.getPlaceAddress());
            activityIndexInfo.setActivity_categorieId(respClubActivity.getCategoryId());
            activityIndexInfo.setActivity_categorieName("");
            if (null != respClubActivity.getPlaceDubboProvider()) {
                activityIndexInfo.setActivity_site(respClubActivity.getPlaceDubboProvider().getName());
            }
            activityIndexInfo.setActivity_cityId(respClubActivity.getCityId());
            activityIndexInfo.setActivity_districtId(respClubActivity.getDistrictId());
            activityIndexInfo.setActivity_lat(respClubActivity.getLat() == null?0:respClubActivity.getLat());
            activityIndexInfo.setActivity_lng(respClubActivity.getLng() == null?0:respClubActivity.getLng());
            activityIndexInfo.setActivity_clubName(respClubActivity.getClubName());
            List<Integer> dateParams = new ArrayList<>();
            ActivityUtils.getDateParams(dateParams, respClubActivity);
            activityIndexInfo.setActivity_dateParams(dateParams);
            activityIndexInfo.setActivity_deadlineTime(respClubActivity.getSignEndTime());
            activityIndexInfo.setActivity_startTime(respClubActivity.getStartTime());
            activityIndexInfo.setActivity_endTime(respClubActivity.getEndTime());
            activityIndexInfo.setActivity_id(respClubActivity.getActivityId() + "");
            if (null != respClubActivity.getSignUserList() && respClubActivity.getLimitNum() > 0) {
                activityIndexInfo.setActivity_isFull(respClubActivity.getSignUserList().size()
                        >= respClubActivity.getLimitNum() ? 1 : 0);
            } else {
                activityIndexInfo.setActivity_isFull(0);//未报满
            }
            activityIndexInfo.setActivity_isPrime(0);
            if(ActivityUtils.isContainPrimeTime(respClubActivity.getStartTime(),
                    respClubActivity.getEndTime()))
            {
                activityIndexInfo.setActivity_isPrime(1);
            }
            activityIndexInfo.setActivity_name(respClubActivity.getName());
            if (null != respClubActivity.getFeeType()) {//收费类型   0 AA收费，1 会员制
                if (respClubActivity.getFeeType().equals(Constants.BYTE_ZERO)) {
                    activityIndexInfo.setActivity_price(respClubActivity.getAaFee().doubleValue());
                } else {
                    List<Double> doubles = new ArrayList<>();
                    doubles.add(respClubActivity.getFemaleMemberFee().doubleValue());
                    doubles.add(respClubActivity.getMaleMemberFee().doubleValue());
                    if(null == respClubActivity.getSignUpType() || respClubActivity.getSignUpType().equals(Constants.BYTE_ZERO))
                    {
                        doubles.add(respClubActivity.getFemaleFee().doubleValue());
                        doubles.add(respClubActivity.getMaleFee().doubleValue());
                    }
                    activityIndexInfo.setActivity_price(CommonUtils.mathUtil(doubles));
                }
            }
            if (null != respClubActivity.getRespActivityPoster()) {
                activityIndexInfo.setActivity_url(respClubActivity.getRespActivityPoster().getUrl());
            }
            String activityPY = ClubNameUtils.getClubNamePinYin(respClubActivity.getName());
            String clubPY = ClubNameUtils.getClubNamePinYin(respClubActivity.getClubName());
            logger.warn("活动拼音：" + activityPY + "俱乐部名字拼音:" + clubPY);
            String activityFirst = activityPY.substring(0, 1);
            String clubFirst = clubPY.substring(0, 1);
            activityIndexInfo.setActivity_clubName_first_letter(clubFirst);
            activityIndexInfo.setActivity_clubName_pinyin(clubPY);
            activityIndexInfo.setActivity_name_first_letter(activityFirst);
            activityIndexInfo.setActivity_name_pinyin(activityPY);
            activityIndexInfo.setClubTask(respClubActivity.getClubTask());
            logger.warn("插入数据：" + JSONObject.toJSONString(activityIndexInfo));
            indexInfoList.add(activityIndexInfo);
        }

        long t1 = System.currentTimeMillis();
        APIResponse res = activitySearchService.insertDocs(indexInfoList);
        if (response == null || !res.isRet()) {
            logger.warn("all 添加俱乐部索引失败");
            logger.warn("返回：" + JSON.toJSON(res));
        } else {
            logger.debug("添加俱乐部all索引成功");
        }

        logger.warn("添加俱乐部all索引，花费：{}", System.currentTimeMillis() - t1);
    }



    @Override
    public void loadClubIndexAll() {
        TbClubExample example = new TbClubExample();
        example.createCriteria()
                .andIsDeleteEqualTo(Constants.IS_DELETE_FALSE);
        List<TbClub> clubList = clubMapper.selectByExample(example);
        List<Integer> clubIds = new ArrayList<>();
        List<Integer> placeIds = new ArrayList<>();
        List<RespClubBaseInfo> clubBaseInfos = new ArrayList<>();

        for (TbClub tbClub : clubList){
            if (tbClub.getIsDelete() == 1){
                continue;
            }
            clubIds.add(tbClub.getId());
            placeIds.add(tbClub.getResidentPlaceId());

            RespClubBaseInfo clubBaseInfo = convert2ClubBaseInfo(tbClub.getId());
            Integer placeId = tbClub.getResidentPlaceId();
            if (tbClub.getResidentPlaceId() != null && tbClub.getResidentPlaceId() != 0) {
                List<RespPlaceLocation> latlng = placeClient.getPlaceLocation(Arrays.asList(placeId));
                if (latlng != null && latlng.size() != 0){
                    double lat = latlng.get(0).getLat();
                    double lng = latlng.get(0).getLng();
                    clubBaseInfo.setLat(lat);
                    clubBaseInfo.setLng(lng);

                    tbClub.setPlaceLat(lat);
                    tbClub.setPlaceLng(lng);
                    clubMapper.updateByPrimaryKeySelective(tbClub);
                }
            }
            Integer activityCount = activitySupportService.countActivityAfterWeek(tbClub.getId());
            clubBaseInfo.setGoingActivityCount(activityCount);
            clubBaseInfo.setStar(clubIntegralService.updateSearchClubStar(tbClub.getId()));
            clubBaseInfos.add(clubBaseInfo);
        }
        executor.submit(new BatchClubSolrIndexThread(clubBaseInfos, clubIds, clubSearchService, true));
    }

    @Override
    public RespClubInfo getClubInfo(int clubId) {
        TbClub tbClub = clubMapper.selectByPrimaryKey(clubId);
        if (tbClub != null){
            return this.convert2ClubInfo(tbClub);
        }
        return null;
    }

    private RespClubInfo convert2ClubInfo(TbClub tbClub){
        RespClubInfo clubInfo = new RespClubInfo();
        clubInfo.setClubId(tbClub.getId());
        clubInfo.setClubName(tbClub.getClubName());
        clubInfo.setCityId(tbClub.getCityId());
        RespCity city = getCity(tbClub.getCityId());
        if (city != null) {
            clubInfo.setCityName(city.getName());
        }
        clubInfo.setDistrictId(tbClub.getDistrictId());
        RespDistrict district = getDistrict(tbClub.getDistrictId());
        if (district != null){
            clubInfo.setDistrictName(district.getName());
        }
        RespUserInfoBase userInfoBase = getUserInfoBase(tbClub.getUid());
        if (userInfoBase != null) {
            clubInfo.setFounder(userInfoBase.getNickName());
            clubInfo.setMobile(userInfoBase.getMobile());
        }
        clubInfo.setCreateTime(tbClub.getCreateTime());
        clubInfo.setPropertyId(tbClub.getClubPropertyId());
        clubInfo.setChildPropertyId(tbClub.getClubPropertyChildId());
        clubInfo.setJoinType(tbClub.getJoinType());
        clubInfo.setIntegral(tbClub.getIntegral());
        clubInfo.setSportTypeId(tbClub.getClubType());
        clubInfo.setStars(tbClub.getStar());
        clubInfo.setLevel(tbClub.getLevel());
        clubInfo.setHomeColor(tbClub.getHomeTeamColor());
        clubInfo.setGuestColor(tbClub.getGuestTeamColor());
        clubInfo.setKm(tbClub.getTotalKm());
        clubInfo.setLogoUrl(tbClub.getLogoUrl());
        clubInfo.setPlaceId(tbClub.getResidentPlaceId());
        clubInfo.setPlaceName(tbClub.getResidentPlaceName());
        clubInfo.setState(tbClub.getIsDelete());
        clubInfo.setFounder(tbClub.getFounderNickname());
        return clubInfo;
    }

    @Override
    public boolean updateClubInfo(ReqClubQuery clubQuery){
        Integer clubId = clubQuery.getClubId();
        if (clubId == null){
            return false;
        }
        TbClub tbClub = new TbClub();
        tbClub.setId(clubId);

        String clubName = clubQuery.getClubName();
        if (!StringUtil.isBlankOrNull(clubName)){
            tbClub.setClubName(clubName);
        }
        Integer sportTypeId = clubQuery.getSportTypeId();
        if (sportTypeId != null){
            tbClub.setClubType(sportTypeId);
            if (sportTypeId == 1){
                tbClub.setSportName("篮球");
            }
            if (sportTypeId == 2){
                tbClub.setSportName("羽毛球");
            }
            if (sportTypeId == 3){
                tbClub.setSportName("足球");
            }
            if (sportTypeId == 4){
                tbClub.setSportName("网球");
            }
            if (sportTypeId == 11){
                tbClub.setSportName("骑行");
            }
            if (sportTypeId == 12){
                tbClub.setSportName("跑步");
            }
        }
        Integer jointype = clubQuery.getJoinType();
        if (jointype != null){
            tbClub.setJoinType(jointype.byteValue());
        }
        Integer residentPlaceId = clubQuery.getResidentPlaceId();
        if (residentPlaceId != null){
            tbClub.setResidentPlaceId(residentPlaceId);
        }
        String placeName = clubQuery.getResidentPlaceName();
        if (!StringUtil.isBlankOrNull(placeName)){
            tbClub.setResidentPlaceName(placeName);
        }

        Integer cityId = clubQuery.getCityId();
        if (cityId != null){
            tbClub.setCityId(cityId);
        }
        Integer districtId = clubQuery.getDistrictId();
        if (districtId != null){
            tbClub.setDistrictId(districtId);
        }
        Integer state = clubQuery.getState();
        if (state != null){
            tbClub.setIsDelete(state.byteValue());
        }
        int ret = clubMapper.updateByPrimaryKeySelective(tbClub);
        if(ret > 0) {

            RespClubBaseInfo clubBaseInfo = convert2ClubBaseInfo(clubId);
            Integer placeId = tbClub.getResidentPlaceId();
            if (placeId != null && placeId != 0){
                List<RespPlaceLocation> latlng = placeClient.getPlaceLocation(Arrays.asList(placeId));
                if (latlng != null && latlng.size() > 0){
                    clubBaseInfo.setLat(latlng.get(0).getLat());
                    clubBaseInfo.setLng(latlng.get(0).getLng());
                }
            }else {
                clubBaseInfo.setLat(tbClub.getPlaceLat());
                clubBaseInfo.setLng(tbClub.getPlaceLng());
            }
            clubBaseInfo.setGoingActivityCount(activitySupportService.countActivityAfterWeek(clubId));
            clubBaseInfo.setStar(clubIntegralService.updateSearchClubStar(clubId));
            System.out.println("-------------更新index----------------" + JSON.toJSON(clubBaseInfo));
            executor.submit(new ClubSolrIndexThread(clubBaseInfo, clubSearchService, true));
            if (state != null && state == 1){
                cppService.pushAdminDeleteClub(clubId);
            }
        }
        return  ret > 0;
    }

    private RespClubBaseInfo convert2ClubBaseInfo(int clubId){
        TbClub club = clubMapper.selectByPrimaryKey(clubId);
        RespClubBaseInfo clubBaseInfo = new RespClubBaseInfo();
        clubBaseInfo.setClubId(club.getId());
        clubBaseInfo.setClubName(club.getClubName());
        clubBaseInfo.setClubType(club.getClubType());
        clubBaseInfo.setSportName(club.getSportName());
        clubBaseInfo.setUsername(club.getFounderNickname());
        clubBaseInfo.setUid(club.getUid());
        RespCity city = new RespCity();
        city.setId(club.getCityId());
        RespCity respCity = getCity(club.getCityId());
        if (respCity != null) {
            city.setName(respCity.getName());
        }
        clubBaseInfo.setCity(city);
        RespDistrict respDistrict = getDistrict(club.getDistrictId());
        if (respDistrict != null) {
            respDistrict.setId(club.getDistrictId());
            respDistrict.setName(respDistrict.getName());
        }
        clubBaseInfo.setDistrict(respDistrict);
        clubBaseInfo.setResidentPlaceId(club.getResidentPlaceId());
        clubBaseInfo.setClubLogo(club.getLogoUrl());
        clubBaseInfo.setStar(null);
        clubBaseInfo.setLevel(club.getLevel());
        clubBaseInfo.setIntegral(club.getIntegral());
        Integer placeId = club.getResidentPlaceId();
        if (placeId != null && placeId != 0) {
            clubBaseInfo.setResidentPlaceId(placeId);
            List<RespPlaceLocation> latlng = placeClient.getPlaceLocation(Arrays.asList(placeId));
            if (latlng != null && latlng.size() > 0){
                clubBaseInfo.setLat(latlng.get(0).getLat());
                clubBaseInfo.setLng(latlng.get(0).getLng());
            }
        }else {
            clubBaseInfo.setLat(club.getPlaceLat());
            clubBaseInfo.setLng(club.getPlaceLng());
        }
        clubBaseInfo.setGoingActivityCount(activitySupportService.countActivityAfterWeek(clubId));
        clubBaseInfo.setStar(clubIntegralService.updateSearchClubStar(clubId));
        return clubBaseInfo;
    }

    @Override
    public PageObj<List<RespClubMemberInfo>> queryClubMemberList(int clubId, boolean isTeam, int pageNo, int pageSize){
        byte team = 0;
        if (isTeam){
            team = 1;
        }
        TbClubMemberExample example = new TbClubMemberExample();
        example.createCriteria()
                .andClubIdEqualTo(clubId)
                .andIsTeamMemberEqualTo(team)
                .andIsDeleteEqualTo(Constants.IS_DELETE_FALSE);
        int total = clubMemberMapper.countByExample(example);
        example.setLimit(Limit.buildLimit(pageNo, pageSize));
        List<TbClubMember> resultList = clubMemberMapper.selectByExample(example);
        List<RespClubMemberInfo> list = new ArrayList<>();
        for (TbClubMember m : resultList) {
//            APIResponse<PageObj<List<ResActivityOrder>>> activityOrder = clubActivityService.activityOrderList(m.getUid(), pageNo, pageSize);
//            PageObj<List<ResActivityOrder>> pageObj = activityOrder.getData();
//            List<ResActivityOrder> respList = pageObj.getItems();
//            BigDecimal signUpCost = null;
//            int signUpActivityCount = 0;
//            int incomeBirdEgg = 0;
//            int useUpBirdEgg = 0;
//            if (null != activityOrder) {
//                for (ResActivityOrder resp : respList) {
//                    signUpCost = resp.getPayAmount();
//                }
//            }
//            TbClubTaskClubEggStreamExample eggStreamExample = new TbClubTaskClubEggStreamExample();
//            eggStreamExample.createCriteria()
//                    .andClubIdEqualTo(clubId)
//                    .andUidEqualTo(m.getUid());
//            List<TbClubTaskClubEggStream> clubTaskClubEggStreamList=clubTaskClubEggStreamMapper.selectByExample(eggStreamExample);
//            for(TbClubTaskClubEggStream tbClubTaskClubEggStream : clubTaskClubEggStreamList){
//                incomeBirdEgg += tbClubTaskClubEggStream.getEgg();
//            }
//            TbClubExample tbClubExample = new TbClubExample();
//            TbClubExample.Criteria criteria = tbClubExample.createCriteria();
//                criteria.andIdEqualTo(clubId);
//            List<TbClub> tbClubList = clubMapper.selectByExample(tbClubExample);
//            for(TbClub tbClub : tbClubList) {
//                TbClubTaskExample
//                        parametersExample = new TbClubTaskExample();
//                parametersExample.createCriteria().andClubTypeEqualTo(tbClub.getClubType());
//                List<TbClubTask> parametersList = clubTaskEggParametersMapper.selectByExample(parametersExample);
//                if(null != parametersList && parametersList.size() > 0) {
//                    for (TbClubTask tbClubTask : parametersList) {
//                        useUpBirdEgg += tbClubTask.getEggForClub();
//                    }
//                }
//            }
//            Map<String, Object> map = new HashMap<String, Object>();
//            map.put("uid",m.getUid());
//            map.put("club",m.getClubId());
//            List<TbClubActivity> clubActivityList=clubActivityMapper.selectTbActivityByUid(map);
//            for(TbClubActivity clubActivity : clubActivityList){
//                TbSignUserExample tbSignUserExample = new TbSignUserExample();
//                tbSignUserExample.createCriteria().andActivityIdEqualTo(
//                        clubActivity.getActivityId()).andIsCancelEqualTo(Constants.ZERO)
//                        .andStatusEqualTo(Constants.IS_YES);
//                signUpActivityCount = signUserMapper.countByExample(tbSignUserExample);
//            }
            RespClubMemberInfo memberInfo = new RespClubMemberInfo();
            memberInfo.setUid(m.getUid());
            memberInfo.setClubId(m.getClubId());
//            memberInfo.setSignUpActivityCount(signUpActivityCount);
//            memberInfo.setSignUpCost(signUpCost);
//            memberInfo.setIncomeBirdEgg(incomeBirdEgg);
//            memberInfo.setUseUpBirdEgg(useUpBirdEgg);
            RespUserInfoDetail userInfo = getUserDetailInfo(m.getUid());
            if (userInfo != null) {
                memberInfo.setNickName(userInfo.getNickName());
                memberInfo.setLevel(userInfo.getLevel());
                memberInfo.setPhone(userInfo.getMobile());
            }
            memberInfo.setRoleCode(m.getRoleCode());
            memberInfo.setMemberLabel(m.getMemberLabelName());

            m.setTeamLabelName(m.getTeamLabelName());
            list.add(memberInfo);
        }

        return PageObj.create(total, pageNo, pageSize, list);
    }

    @Override
    public APIResponse updateClubMember(RespClubMemberInfo info) {

        TbClubMemberExample example = new TbClubMemberExample();

        TbClubMemberExample.Criteria criteria = example.createCriteria();
        criteria.andClubIdEqualTo(info.getClubId())
                .andUidEqualTo(info.getUid()).andIsDeleteEqualTo(Constants.IS_DELETE_FALSE);

        TbClubMember record = new TbClubMember();

        String memberLabel = info.getMemberLabel();
        if (!StringUtil.isBlankOrNull(memberLabel)) {
            record.setMemberLabelName(memberLabel);
        }
        String teamLabel = info.getTeamLabel();
        if (!StringUtil.isBlankOrNull(teamLabel)){
            record.setTeamLabelName(teamLabel);
        }
        String roleCode = info.getRoleCode();
        if (!StringUtil.isBlankOrNull(roleCode)) {
            record.setRoleCode(roleCode);
        }
        Boolean isTeam = info.getTeamMember();
        if (isTeam != null){
            if (isTeam){
                //判断是否此俱乐部代表队成员已满，判断此成员是否可以加入此类型的俱乐部代表队
               boolean canjoin = clubMemberService.canJoinClubTeam(info.getUid(), info.getClubId());
                if (!canjoin){
                    return APIResponse.returnFail("成员"+info.getUid()+"不能加入俱乐部"+info.getClubId()+"代表队，已经加入此类型的或者此俱乐部代表队已满");
                }
            }
            record.setIsTeamMember(isTeam?(byte)1:(byte)0);
        }
        clubMemberMapper.updateByExampleSelective(record, example);

        return APIResponse.returnSuccess();
    }

    @Override
    public PageObj<List<TbClubSystemLogo>> queryClubSystemLogo(int sportTypeId, int pageNo, int pageSize){

        TbClubSystemLogoExample example = new TbClubSystemLogoExample();
        example.createCriteria()
                .andClubTypeIdEqualTo(sportTypeId).andIsDeleteEqualTo(Constants.IS_DELETE_FALSE);
        int total = clubSystemLogoMapper.countByExample(example);
        example.setPage(new Page((pageNo-1)*pageSize, pageSize));
        return PageObj.create(total, pageNo, pageSize,
                clubSystemLogoMapper.selectByExample(example));
    }

    @Override
    public APIResponse deleteClubMember(int clubId, int uid, int larkAppId) {

        boolean ret = clubMemberService.fuckoutClub(clubId, uid, -1,larkAppId);
        if (ret) return APIResponse.returnSuccess();
        return APIResponse.returnFail("删除失败");
    }

    @Override
    public PageObj<List<RespWithdrawRecord>> queryWithdrawRecord(ReqClubFinanceQuery query){

        TbClubWithdrawalsRecordExample example = new TbClubWithdrawalsRecordExample();
        TbClubWithdrawalsRecordExample.Criteria criteria = example.createCriteria();

        Date startTime = query.getStartTime();
        if (startTime != null){
            logger.warn("startTime=" + sf.format(startTime));
            criteria.andCreateTimeGreaterThanOrEqualTo(startTime);
        }
        Date endTime = getEndTime(startTime, query.getEndTime());
        if (endTime != null){
            logger.warn("endTime" + sf.format(endTime));
            criteria.andCreateTimeLessThan(endTime);
        }
        Integer clubId = query.getClubId();
        if (clubId != null){
            criteria.andClubIdEqualTo(clubId);
        }
        Integer opType = query.getOpType();
        if (opType != null){

        }
        criteria.andIsDeleteEqualTo(Constants.IS_DELETE_FALSE);

        int total = clubWithdrawalsRecordMapper.countByExample(example);
        int pageNo = query.getPageNo();
        int pageSize = query.getPageSize();
        example.setLimit(Limit.buildLimit(pageNo, pageSize));

        List<TbClubWithdrawalsRecord> resultList = clubWithdrawalsRecordMapper.selectByExample(example);
        List<RespWithdrawRecord> list = new ArrayList<>();
        for (TbClubWithdrawalsRecord record : resultList){
            RespWithdrawRecord _record = new RespWithdrawRecord();
            _record.setTime(record.getCreateTime());
            TbClub club = clubMapper.selectByPrimaryKey(record.getClubId());
            _record.setClubName(club!=null?club.getClubName():"");
            _record.setPayType(record.getAccountType());
            _record.setAmount(record.getMoney());
            _record.setBalance(record.getBalance());
            RespUserInfoBase userinfo = getUserInfoBase(record.getUid());
            if (userinfo != null){
                String realName = userinfo.getRealName();
                if (StringUtil.isBlankOrNull(realName)){
                    _record.setOperator(userinfo.getNickName());
                }
                _record.setOperator(realName);
            }
            list.add(_record);
        }
        return PageObj.create(total, pageNo, pageSize, list);
    }

    @Override
    public List<TbClub> autoPrompting(String clubName) {
        if (StringUtil.isBlankOrNull(clubName)){
            return new ArrayList<>();
        }
        TbClubExample example = new TbClubExample();
        example.createCriteria().andClubNameLike(clubName+"%");    //前面不加百分号，以至于不走索引
        example.setOrderByClause(" id desc");
        List<TbClub> resultList = clubMapper.selectByExample(example);
        if (resultList == null){
            return new ArrayList<>();
        }
        if (resultList.size() > 10){
            return resultList.subList(0, 10);
        }else {
            return resultList;
        }
    }

    @Override
    public PageObj<List<RespClubMemberFinaceStream>> queryClubMemberFinaceStream(ReqClubFinanceQuery query) {

        Map<String, Object> paramMap = new HashMap<>();
        Date startTime = query.getStartTime();
        if (startTime != null){
            logger.warn("startTime=" + sf.format(startTime));
            paramMap.put("startTime", startTime);
        }
        Date endTime = getEndTime(startTime, query.getEndTime());
        if (endTime != null){
            logger.warn("endTime" + sf.format(endTime));
            paramMap.put("endTime", endTime);
        }
        Integer clubId = query.getClubId();
        if (clubId != null){
            paramMap.put("clubId", clubId);
        }
        Integer uid = query.getMemberUid();
        if (uid != null){
            paramMap.put("uid", uid);
        }
        int pageNo = query.getPageNo();
        int pageSize = query.getPageSize();
        paramMap.put("start", (pageNo-1)*pageSize);
        paramMap.put("pageSize", pageSize);

        List<RespClubMemberFinaceStream> resultList = sqlSessionTemplate.selectList("queryClubMemberFinanceStreamList", paramMap);
        for (RespClubMemberFinaceStream stream : resultList){
            stream.setClubName(getClubName(stream.getClubId()));
            RespUserInfoBase userinfo = getUserInfoBase(stream.getUid());
            if (userinfo != null) {
                stream.setNickName(userinfo.getNickName());
            }
        }
        int total = sqlSessionTemplate.selectOne("countClubMemberFinanceStreamList", paramMap);

        return PageObj.create(total, pageNo, pageSize, resultList);
    }

    @Override
    public PageObj<List<RespClubActivityFinaceStream>> queryClubActFinaceStream(ReqClubFinanceQuery query){
        TbClubActivitySettlementExample example = new TbClubActivitySettlementExample();
        TbClubActivitySettlementExample.Criteria criteria = example.createCriteria();
        Date startTime = query.getStartTime();
        if (startTime != null){
            logger.warn("startTime=" + sf.format(startTime));
            criteria.andCreateTimeGreaterThanOrEqualTo(startTime);
        }
        Date endTime = getEndTime(startTime, query.getEndTime());
        if (endTime != null){
            logger.warn("endTime" + sf.format(endTime));
            criteria.andCreateTimeLessThan(endTime);
        }
        Integer clubId = query.getClubId();
        if (clubId != null){
            criteria.andClubIdEqualTo(clubId);
        }
        Integer activityId = query.getActivityId();
        if (activityId != null){
            criteria.andActivityIdEqualTo(activityId);
        }
        int total = clubActivitySettlementMapper.countByExample(example);
        int pageNo = query.getPageNo();
        int pageSize = query.getPageSize();
        example.setLimit(Limit.buildLimit(pageNo, pageSize));
        List<TbClubActivitySettlement> resultList = clubActivitySettlementMapper.selectByExample(example);
        List<RespClubActivityFinaceStream> list = new ArrayList<>();
        for (TbClubActivitySettlement settlement : resultList){
            RespClubActivityFinaceStream stream = new RespClubActivityFinaceStream();
            stream.setTime(settlement.getCreateTime());
            stream.setClubName(getClubName(settlement.getClubId()));
            ActivityInfo activityInfo = activityOpenService.queryOneActivityById(settlement.getActivityId());
            if (activityInfo != null) {
                stream.setActivityName(activityInfo.getName());
            }
            BigDecimal onlineAmount = settlement.getPayMoney().add(settlement.getAccumulateMoney()).add(settlement.getIntegralMoney());
            //线下收入在tb_club_offline_account_stream表记录
            BigDecimal offlineAmount = calculateActOffineTotalAmount(settlement.getClubId(), settlement.getActivityId());
            stream.setOnlineAmount(onlineAmount);
            stream.setOfflineAmount(offlineAmount);
            stream.setTotalAmount(offlineAmount.add(onlineAmount));
            list.add(stream);
        }

        return PageObj.create(total, pageNo, pageSize, list);
    }

    private Date getStartTime(Date startTime){

        if (startTime != null){
            try {
                return sf.parse(sf.format(startTime));
            } catch (ParseException e) {
                return null;
            }
        }
        return startTime;
    }
    private Date getEndTime(Date startTime, Date endTime){
        if (endTime != null){
            endTime = getStartTime(endTime);

            Calendar cal = Calendar.getInstance();
            cal.setTime(endTime);
            cal.add(Calendar.HOUR_OF_DAY, 24);
            endTime = cal.getTime();
        }
        return endTime;
    }
    private Date getStartQueryTime(Date startQueryTime){

        if (startQueryTime != null){
            try {
                return sf.parse(sf.format(startQueryTime));
            } catch (ParseException e) {
                return null;
            }
        }
        return startQueryTime;
    }

    private Date getEndQueryTime(Date startQueryTime, Date endQueryTime){
        if (endQueryTime != null){
            endQueryTime = getStartQueryTime(endQueryTime);

            Calendar cal = Calendar.getInstance();
            cal.setTime(endQueryTime);
            cal.add(Calendar.HOUR_OF_DAY, 24);
            endQueryTime = cal.getTime();
        }
        return endQueryTime;
    }
    private String getClubName(int clubId){
        TbClub club = clubMapper.selectByPrimaryKey(clubId);
        if (club != null){
            return club.getClubName();
        }
        return "";
    }

    private BigDecimal calculateActOffineTotalAmount(int clubId, int activityId){
        BigDecimal offlineTotal = BigDecimal.ZERO;
        TbClubOfflineAccountStreamExample example = new TbClubOfflineAccountStreamExample();
        example.createCriteria()
                .andClubIdEqualTo(clubId).andActivityIdEqualTo(activityId).andIsDeleteEqualTo(Constants.IS_DELETE_FALSE);
        List<TbClubOfflineAccountStream> resultList = clubOfflineAccountStreamMapper.selectByExample(example);
        if (resultList != null && resultList.size()>0){
            for (TbClubOfflineAccountStream stream : resultList){
                offlineTotal.add(stream.getIncomeOffline());
            }
        }
        return offlineTotal;
    }

    @Override
    public PageObj<List<RespClubFinanceReprot>> queryClubFinanceReport(ReqClubFinanceQuery query){

        Map<String, Object> map = new HashMap<>();
        Integer cityId = query.getCityId();
        if (cityId != null){
            map.put("cityId", cityId);
        }
        Integer clubId = query.getClubId();
        if (clubId != null){
            map.put("clubId", clubId);
        }
        Integer sportTypeId = query.getSportTypeId();
        if (sportTypeId != null){
            map.put("sportTypeId", sportTypeId);
        }
        Date startTime = query.getStartTime();
        if (startTime != null){
            logger.warn("startTime=" + sf.format(startTime));
            map.put("startTime", startTime);
        }
        Date endTime = query.getEndTime();
        if (endTime != null){
            logger.warn("startTime=" + sf.format(endTime));
            map.put("endTime", endTime);
        }
        int total = sqlSessionTemplate.selectOne("countClubFinanceReport", map);
        int pageNo = query.getPageNo();
        int pageSize = query.getPageSize();
        map.put("start",( pageNo-1)*pageSize);
        map.put("pageSize", pageSize);
        List<RespClubFinanceReprot> resultList = sqlSessionTemplate.selectList("queryClubFinanceReport", map);
        for (RespClubFinanceReprot report : resultList){
            RespCity city = getCity(report.getCityId());
            if (city != null) {
                report.setCityName(city.getName());
            }
            BigDecimal totalAmount = BigDecimal.ZERO;
            if (report.getOnlineAmount() != null){
                totalAmount =totalAmount.add(report.getOnlineAmount());
            }
            if (report.getOfflineAmount() != null){
                totalAmount = totalAmount.add(report.getOfflineAmount());
            }
            report.setTotalAmount(totalAmount);
            BigDecimal memberTotal = BigDecimal.ZERO;
            if (report.getMemberRechargeonline() != null){
                memberTotal = memberTotal.add(report.getMemberRechargeonline());
            }
            if (report.getMemberRechargeoffline() != null){
                memberTotal = memberTotal.add(report.getMemberRechargeoffline());
            }
            report.setMemberRechargeAmount(memberTotal);
        }
        return PageObj.create(total, pageNo, pageSize, resultList);
    }

    /**
     * 获取俱乐部在线充值明细
     * @param query
     * @return
     */
    @Override
    public PageObj<List<RespClubRechargeStream>> queryClubRechargeStream(ReqClubRechargeQuery query) {
        Map<String ,Object> param = new HashMap<>();

        int pageNo = query.getPageNo();
        int pageSize = query.getPageSize();
        //俱乐部名称搜索
        String clubName = query.getClubName();
        if (StringUtils.isNotBlank(clubName)) {
            TbClub club = this.getClubByName(query.getClubName());
            if (club != null) {
                param.put("clubId",club.getId());
            } else {
                PageObj.create(0,pageNo,pageSize,new ArrayList<>());
            }
        }
        //俱乐部ID搜索
        if (query.getClubId() != null && query.getClubId() != 0) {
            param.put("clubId",query.getClubId());
        }
        //充值手机搜索
        String mobile = query.getMobile();
        if (StringUtils.isNotBlank(mobile)) {
            RespUserInfoBase response = super.getUserInfoByMobile(mobile);
            if (response != null) {
                param.put("uid",response.getUid());
            } else {
                PageObj.create(0,pageNo,pageSize,new ArrayList<>());
            }
        }
        //订单号搜索
        String outTradeNo = query.getOutTradeNo();
        if (StringUtils.isNotBlank(outTradeNo)) {
            param.put("outTradeNo",outTradeNo);
        }
        //开始结束日期搜索
        if (query.getStartTime() != null && query.getEndTime() != null) {
            param.put("createTimeStart", DateUtils.dayBegin(query.getStartTime()));
            param.put("createTimeEnd",DateUtils.dayEnd(query.getEndTime()));
        }
        //支付渠道搜索
        if (query.getPayChannel() != null && query.getPayChannel() != 0) {
            param.put("payChannel",query.getPayChannel());
        }
        //订单状态搜索
        if (query.getStatusList() != null && !query.getStatusList().isEmpty()) {
          param.put("statusList",query.getStatusList());
        }
        Integer total = this.clubAccountExtendMapper.getClubOnlineMemberRechargeStreamCount(param);

        param.put("start",pageNo*pageSize);
        param.put("pageSize", pageSize);
        List<RespClubRechargeStream> streams = this.clubAccountExtendMapper.getClubOnlineMemberRechargeStream(param);
        List<Integer> uids = new ArrayList<>();
        for (RespClubRechargeStream stream : streams) {
            uids.add(stream.getUid());
        }
        Map<Integer,RespUserInfoBase> userInfoBaseMap = userServiceFacade.batchQueryUserInfoToMap(uids);
        for (RespClubRechargeStream stream : streams) {
            if (userInfoBaseMap == null) {
                stream.setNickName("");
                stream.setMobile("");
            } else {
                RespUserInfoBase respUserInfoBase = userInfoBaseMap.get(stream.getUid());
                if (respUserInfoBase != null) {
                    stream.setNickName(respUserInfoBase.getNickName());
                    stream.setMobile(respUserInfoBase.getMobile());
                } else {
                    stream.setNickName("");
                    stream.setMobile("");
                }
            }
        }
        return PageObj.create(total,pageNo,pageSize,streams);
    }

    @Override
    public boolean add(ReqMultimediaAdd reqMultimediaAdd,int uid) {

        if (reqMultimediaAdd == null) {
            return true;
        } else {
            int n = 0;
                int i = this.insertClubMultimedia(reqMultimediaAdd,uid);
                n = n + i;
            return n > 0;
        }
    }

    /**
     * 添加俱乐部相册
     * @param reqMultimediaAdd
     * @return
     */
    private int insertClubMultimedia(ReqMultimediaAdd reqMultimediaAdd,int uid){
        TbClubMultimedia clubMultimedia = new TbClubMultimedia();
        clubMultimedia.setUid(uid);
        clubMultimedia.setMultimediaUrl(reqMultimediaAdd.getMultimediaUrl());
        clubMultimedia.setClubId(reqMultimediaAdd.getClubId());
        if(reqMultimediaAdd.getMultimediaType().getBytes().length !=0){
            clubMultimedia.setMultimediaType((byte) 1);
        }
        clubMultimedia.setIsDelete((byte) 0);
        int total=clubMultimediaMapper.insertSelective(clubMultimedia);
        return total;
    }
    private TbClub getClubByName(String clubName){
        TbClubExample example = new TbClubExample();
        TbClubExample.Criteria criteria = example.createCriteria();
        criteria.andClubNameEqualTo(clubName);
        List<TbClub> clubList = clubMapper.selectByExample(example);
        if (clubList.isEmpty()) {
            return null;
        } else {
            return clubList.get(0);
        }
    }

    public List<RespClubFinanceReconciliationVo> exportClubFinanceReconciliationList(ReqClubFinanceReconciliationQuery query){

        Map<String, Object> paramMap = new HashMap<>();
        Integer cityId = query.getCityId();
        if (cityId != null && cityId != 0){
            paramMap.put("cityId", cityId);
        }
        Integer clubId = query.getClubId();
        if (clubId != null && clubId != 0){
            paramMap.put("clubId", clubId);
        }
        String clubName = query.getClubName();
        if (!StringUtil.isBlankOrNull(clubName)){
            paramMap.put("clubName", clubName);
        }
        String phone = query.getPhone();
        if (!StringUtil.isBlankOrNull(phone)){
            RespUserInfoBase userInfo = getUserInfoByMobile(phone);
            if (userInfo != null) {
                paramMap.put("uid", userInfo.getUid());
            }
        }
        Date startTime = getStartTime(query.getStartTime());
        if (startTime != null){
            paramMap.put("startTime", startTime);
        }
        Date endTime = getEndTime(query.getStartTime(), query.getEndTime());
        if (endTime != null){
            paramMap.put("endTime", endTime);
        }
        List<RespClubFinanceReconciliationVo> resultList = sqlSessionTemplate.selectList("exportClubFinanceReconciliationList", paramMap);

        if (resultList == null || resultList.size() == 0){
            return new ArrayList<>();
        }

        List<Integer> uids = new ArrayList<>();
        List<Integer> clubIds = new ArrayList<>();

        for(RespClubFinanceReconciliationVo vo : resultList) {
            clubIds.add(vo.getClubId());
        }

        Map<Integer, Map<Integer, Date>> clubIdActivityIds = new HashMap<Integer, Map<Integer, Date>>();
        Map<Integer, BigDecimal> clubIdAmount_S = new HashMap<Integer, BigDecimal>();
        Map<Integer, BigDecimal> clubIdAmount_N = new HashMap<Integer,BigDecimal>();

        if (clubIds.size() > 0) {
            clubIdActivityIds = queryAlreadySettleActivityIds(clubIds, startTime, endTime);
            clubIdAmount_S = getWithdraw_SAmount(clubIds, startTime, endTime);
            clubIdAmount_N = getCustomWithdraw_NAmount(clubIds, startTime, endTime);
        }

        for (RespClubFinanceReconciliationVo vo : resultList){
            Map<Integer, Date> activityIdUpdateTime = clubIdActivityIds.get(vo.getClubId());    //已经结算的活动
            if (CollectionUtils.isEmpty(activityIdUpdateTime)) {
                continue;
            }

            List<Integer> activityIds = new ArrayList<>();
            List<Integer> refundActivityIds = new ArrayList<>();
            for (Map.Entry<Integer, Date> entry : activityIdUpdateTime.entrySet()) {
                if(entry.getValue().getTime() < AA_SETTLEMENT_DEADLINE) {
                    refundActivityIds.add(entry.getKey());
                }
                activityIds.add(entry.getKey());
            }
            vo = subtractAARefundFee(vo, refundActivityIds); //将AA退款部分减掉

            uids.add(vo.getUid());
            BigDecimal drawAmount_s = clubIdAmount_S.get(vo.getClubId());
            if (drawAmount_s == null) {
                drawAmount_s = BigDecimal.ZERO;
            }

            BigDecimal drawAmount_n = clubIdAmount_N.get(vo.getClubId());
            if (drawAmount_n == null) {
                drawAmount_n = BigDecimal.ZERO;
            }
            vo.setWithdrawAmount_S(drawAmount_s);
            vo.setWithdrawAmount_N(drawAmount_n);

            //处理balanceAmount+eggAmount+payAmount ！= withdrawAmount_N+withdrawAmount_S 的情况
            if (false == vo.getBalanceAmount().add(vo.getEggAmount()).add(vo.getPayAmount()).setScale(2, BigDecimal.ROUND_HALF_UP).equals(
                    vo.getWithdrawAmount_N().add(vo.getWithdrawAmount_S()).setScale(2, BigDecimal.ROUND_HALF_UP))) {
                List<Integer> activityIds2 = queryAlreadySettleActivityIds2(vo.getClubId(), startTime, endTime);
                logger.warn("exportClubFinanceReconciliationList: clubId:{}, clubActivitySettlement activityIds:{}, clubOnlineAccountStream activityIds:{}," ,
                        vo.getClubId(), activityIds.size(), activityIds2.size());
                List<Integer> maxActivityIds = null;
                List<Integer> minActivityIds = null;
                if (activityIds.size() == activityIds2.size()) {
                    continue;
                }
                if (activityIds.size() > activityIds2.size()) {
                    maxActivityIds = activityIds;
                    minActivityIds = activityIds2;
                } else {
                    maxActivityIds = activityIds2;
                    minActivityIds = activityIds;
                }
                maxActivityIds.removeAll(minActivityIds);

                //have duplicate avtivityIds when size == 0
                if (maxActivityIds.size() > 0) {
                    vo = subtractAARefundFee(vo, maxActivityIds); //将AA退款部分减掉
                    RespClubFinanceReconciliationVo voToAdd = new RespClubFinanceReconciliationVo();
                    HashMap<String, Object > map = new HashMap<>();
                    map.put("clubId", vo.getClubId());
                    map.put("activityIds", maxActivityIds);
                    voToAdd = sqlSessionTemplate.selectOne("queryClubFinanceSummary", map);
                    if (voToAdd != null) {
                        vo.setEggAmount(vo.getEggAmount().add(voToAdd.getEggAmount()));
                        vo.setBalanceAmount(vo.getBalanceAmount().add(voToAdd.getBalanceAmount()));
                        vo.setPayAmount(vo.getPayAmount().add(voToAdd.getPayAmount()));
                    } else {
                        logger.warn("exportClubFinanceReconciliationList: clubId: {}, diff activityIds:{} but have no data return in queryClubFinanceSummary",
                                vo.getClubId(), maxActivityIds);
                    }
                }
            }
        }

        List<RespUserInfoBase> list = new ArrayList<>();
        APIResponse<List<RespUserInfoBase>> response = userServiceFacade.batchQueryUserInfo(uids);
        if (response != null && response.isRet()){
              list = response.getData();
        }
        Map<Integer, String> uidPhoneMap = new HashMap<>();
        if (list.size() > 0){
            for (RespUserInfoBase userInfoBase : list){
                if (userInfoBase == null){
                    continue;
                }
                uidPhoneMap.put(userInfoBase.getUid(), userInfoBase.getMobile());
            }
        }

        for (RespClubFinanceReconciliationVo vo : resultList){
            vo.setClubFounderPhone(uidPhoneMap.get(vo.getUid()));
            int _cityId = vo.getCityId();
            if (_cityId == 1) {
                vo.setCityName("北京");
            }
            if (_cityId == 2){
                vo.setCityName("上海");
            }
            if (_cityId == 3){
                vo.setCityName("杭州");
            }
            if (_cityId == 4){
                vo.setCityName("广州");
            }
            if (_cityId == 5){
                vo.setCityName("成都");
            }
            if (_cityId == 6){
                vo.setCityName("深圳");
            }
        }

        return resultList;
    }

    @Override
    public RespClubFinanceSummaryVo queryClubFinanceReconciliationList(
            ReqClubFinanceReconciliationQuery query){

        RespClubFinanceSummaryVo summaryVo = new RespClubFinanceSummaryVo();

        TbClubExample example = new TbClubExample();
        TbClubExample.Criteria criteria = example.createCriteria();
        Integer cityId = query.getCityId();
        if (cityId != null && cityId > 0){
            criteria.andCityIdEqualTo(cityId);
        }
        Integer clubId = query.getClubId();
        if (clubId != null && clubId > 0){
            criteria.andIdEqualTo(clubId);
        }
        String clubName = query.getClubName();
        if (!StringUtil.isBlankOrNull(clubName)){
            criteria.andClubNameLike("%"+clubName+"%");
        }
        String phone = query.getPhone();
        if (!StringUtil.isBlankOrNull(phone)){
            //手机号查
            RespUserInfoBase userInfo = getUserInfoByMobile(phone);
            if (userInfo != null){
                criteria.andUidEqualTo(userInfo.getUid());
            }else {
                return summaryVo;
                //throw new BizException("查询不到此手机号的用户！");
            }
        }
        Date startTime = null;
        Date endTime = null;
        if(null != query.getStartTime() && null != query.getEndTime())
        {
            startTime = getStartTime(query.getStartTime());
            endTime = getEndTime(startTime, query.getEndTime());
        }
        int total = clubMapper.countByExample(example);
        int pageNo = query.getPageNo();
        int pageSize = query.getPageSize();
        example.setOrderByClause("id desc");
        example.setLimit(Limit.buildLimit(pageNo, pageSize));
        List<TbClub> clubList = clubMapper.selectByExample(example);
        logger.warn("Query:" + JSONObject.toJSONString(query));
        List<RespClubFinanceReconciliationVo> resultList = new ArrayList<>();

        List<Integer> clubIds = new ArrayList<>();

        for(TbClub club : clubList) {
            clubIds.add(club.getId());
        }

        Map<Integer, Map<Integer, Date>> clubIdActivityIds = new HashMap<Integer, Map<Integer, Date>>();

        if (clubList.size() > 0) {
            clubIdActivityIds = queryAlreadySettleActivityIds(clubIds, startTime, endTime);
        }

        for (TbClub club: clubList){
            long t1 = System.currentTimeMillis();
            HashMap<String, Object> map = new HashMap<>();
            map.put("clubId", club.getId());

            List<Integer> activityIds1 = new ArrayList<>();    //已经结算的活动, 结算表
            List<Integer> refundActivityIds = new ArrayList<>();    //已经结算的活动, 结算表
            Map<Integer, Date> activityIdUpdateTime = clubIdActivityIds.get(club.getId());    //已经结算的活动
            if (!CollectionUtils.isEmpty(activityIdUpdateTime)) {
                for (Map.Entry<Integer, Date> entry : activityIdUpdateTime.entrySet()) {
                    if(entry.getValue().getTime() < AA_SETTLEMENT_DEADLINE) {
                        refundActivityIds.add(entry.getKey());
                    }
                    activityIds1.add(entry.getKey());
                }
            }

            List<Integer> activityIds2 = queryAlreadySettleActivityIds2(club.getId(), startTime, endTime);    //已经结算的活动, 流水表
            if (activityIds1.size() != activityIds2.size()){
                logger.warn("exportClubFinanceReconciliationList: clubId:{}, clubActivitySettlement activityids:{}, clubOnlineAccountStream activityids:{}," ,
                        club.getId(), activityIds1.size(), activityIds2.size());
            }
            List<Integer> maxActivityIds = activityIds1.size() > activityIds2.size() ?activityIds1 : activityIds2;
            logger.warn("-------已经结算的俱乐部活动id：{}", maxActivityIds);
            RespClubFinanceReconciliationVo vo = null;
            if (maxActivityIds.size() > 0){
                map.put("activityIds", maxActivityIds);
                long t0 = System.currentTimeMillis();
                vo = sqlSessionTemplate.selectOne("queryClubFinanceSummary", map);
                vo = subtractAARefundFee(vo, maxActivityIds); //将AA退款部分减掉
                if (refundActivityIds.size() > 0) {
                    vo = subtractAARefundFee(vo, refundActivityIds);
                }
            }

            if (vo == null){
                vo = new RespClubFinanceReconciliationVo();
            }
            vo.setClubId(club.getId());
            vo = addGameFee(vo, club.getId(), startTime, endTime);    //将俱乐部赛事结算的钱加上

            vo.setClubId(club.getId());
            vo.setClubName(club.getClubName());
            RespUserInfoBase userInfo = getUserInfoBase(club.getUid());
            if (userInfo != null) {
                vo.setClubFounderPhone(userInfo.getMobile());
                vo.setClubFounderName(userInfo.getRealName());
            }
            vo.setCityId(club.getCityId());
            vo.setCityName(getCity(club.getCityId()).getName());

            TbClubWithdrawalsRecordExample example1 = new TbClubWithdrawalsRecordExample();
            TbClubWithdrawalsRecordExample.Criteria criteria1 = example1.createCriteria();
            criteria1.andClubIdEqualTo(club.getId());  //提现成功
            if (startTime != null){
                criteria1.andCreateTimeGreaterThan(startTime);
            }
            if (endTime != null){
                criteria1.andCreateTimeLessThanOrEqualTo(endTime);
            }
            BigDecimal withdrawAmount_S_total = BigDecimal.ZERO;
            List<TbClubWithdrawalsRecord> resultList1 = clubWithdrawalsRecordMapper.selectByExample(example1);
            for (TbClubWithdrawalsRecord record : resultList1){
                withdrawAmount_S_total= withdrawAmount_S_total.add(record.getMoney());
            }
            vo.setWithdrawAmount_S(withdrawAmount_S_total);   //提现成功金额

            TbClubOnlineAccountStreamExample onsExample = new TbClubOnlineAccountStreamExample();
            TbClubOnlineAccountStreamExample.Criteria criteria2 = onsExample.createCriteria();
            criteria2.andClubIdEqualTo(club.getId());
            if (startTime != null){
                criteria2.andCreateTimeGreaterThan(startTime);
            }
            if (endTime != null){
                criteria2.andCreateTimeLessThanOrEqualTo(endTime);
            }
            onsExample.setOrderByClause(" id desc");
            List<TbClubOnlineAccountStream> list = clubOnlineAccountStreamMapper.selectByExample(onsExample);
            if (list != null && list.size() > 0) {
                vo.setWithdrawAmount_N(list.get(0).getSufAmount());
            }else {
                vo.setWithdrawAmount_N(BigDecimal.ZERO);
            }
            logger.warn("-----------clubId=", club.getId() + ", cost=" + (System.currentTimeMillis()-t1));
            resultList.add(vo);
        }

        summaryVo.setListPageObj(PageObj.create(total, pageNo, pageSize, resultList));
        summaryVo = getSummaryVo(summaryVo,cityId, clubId, startTime, endTime); //计算汇总
        return summaryVo;
    }

    private Map<Integer, BigDecimal> getWithdraw_SAmount(List<Integer> clubIds, Date startTime, Date endTime){
        TbClubWithdrawalsRecordExample example1 = new TbClubWithdrawalsRecordExample();
        TbClubWithdrawalsRecordExample.Criteria criteria1 = example1.createCriteria();
        criteria1.andClubIdIn(clubIds);  //提现成功
        if (startTime != null){
            criteria1.andCreateTimeGreaterThan(startTime);
        }
        if (endTime != null){
            criteria1.andCreateTimeLessThanOrEqualTo(endTime);
        }
        List<TbClubWithdrawalsRecord> resultList1 = clubWithdrawalsRecordMapper.selectByExample(example1);

        Map<Integer, BigDecimal> clubIdAmount_S = new HashMap<Integer,BigDecimal>();
        if (!CollectionUtils.isEmpty(resultList1)) {
            for (TbClubWithdrawalsRecord record : resultList1){
                Integer key = record.getClubId();
                BigDecimal value = record.getMoney();
                if (!clubIdAmount_S.containsKey(key)) {
                    clubIdAmount_S.put(key, value);
                } else {
                    clubIdAmount_S.put(key, clubIdAmount_S.get(key).add(value));
                }
            }
        }
        return clubIdAmount_S;
    }


    private Map<Integer, BigDecimal> getCustomWithdraw_NAmount(List<Integer> clubIds, Date startTime, Date endTime){
        Map<String, Object> paramMap = new HashMap<>();
        paramMap.put("clubIds", clubIds);
        paramMap.put("startTime", startTime);
        paramMap.put("endTime", endTime);
        List<TbClubOnlineAccountStream> list = sqlSessionTemplate.selectList("queryClubSufAmount", paramMap);

        Map<Integer, BigDecimal> clubIdAmount_N = new HashMap<Integer,BigDecimal>();
        if (!CollectionUtils.isEmpty(list)) {
            for (TbClubOnlineAccountStream record : list){
                Integer key = record.getClubId();
                BigDecimal value = record.getSufAmount();
                if (!clubIdAmount_N.containsKey(key)) {
                    clubIdAmount_N.put(key, value);
                } else {
                    logger.warn("getCustomWithdraw_NAmount: clubId:{}, preNAmount:{}, NAmount:{}, Id:{}, SHOULD NOT happend",
                            clubIdAmount_N.get(key), value, record.getClubId());
                    clubIdAmount_N.put(key, record.getSufAmount());
                }
            }
        }
        return clubIdAmount_N;
    }

    private BigDecimal getWithdraw_NAmount(Integer clubId, Date startTime, Date endTime){
        TbClubOnlineAccountStreamExample onsExample = new TbClubOnlineAccountStreamExample();
        TbClubOnlineAccountStreamExample.Criteria criteria2 = onsExample.createCriteria();
        criteria2.andClubIdEqualTo(clubId);
        if (startTime != null){
            criteria2.andCreateTimeGreaterThan(startTime);
        }
        if (endTime != null){
            criteria2.andCreateTimeLessThanOrEqualTo(endTime);
        }
        onsExample.setOrderByClause(" id desc");
        onsExample.setLimitEnd(1);
        List<TbClubOnlineAccountStream> list = clubOnlineAccountStreamMapper.selectByExample(onsExample);
        if (list != null && list.size() > 0) {
            return list.get(0).getSufAmount();
        }else {
            return BigDecimal.ZERO;
        }
    }

    private RespClubFinanceReconciliationVo addGameFee(RespClubFinanceReconciliationVo vo, Integer clubId, Date startTime, Date endTime){

        if (clubId == null){
            return vo;
        }
        //logger.warn("----" + DateTimeUtils.convertDate2String("yyyy-MM-dd HH:mm:ss", startTime) + "-----" + DateTimeUtils.convertDate2String("yyyy-MM-dd HH:mm:ss", endTime));
        TbClubOnlineAccountStreamExample example = new TbClubOnlineAccountStreamExample();
        TbClubOnlineAccountStreamExample.Criteria criteria = example.createCriteria();
        criteria
                .andClubIdEqualTo(clubId)
                .andTypeEqualTo((byte)3);  //运动场结算
        if (startTime != null){
            criteria.andCreateTimeGreaterThan(startTime);
        }
        if (endTime != null){
            criteria.andCreateTimeLessThanOrEqualTo(endTime);
        }
        List<TbClubOnlineAccountStream> streams = clubOnlineAccountStreamMapper.selectByExample(example);
        BigDecimal seggAmount = BigDecimal.ZERO;
        BigDecimal spayAmount = BigDecimal.ZERO;
        for (TbClubOnlineAccountStream stream : streams){
            List<RespGameOrder> result = stadiumOpenService.queryOrderNoByGameId(stream.getActivityId());
            if (result == null || result.size() == 0) {
                continue;
            }
            BigDecimal eggAmount = BigDecimal.ZERO;
            BigDecimal payAmount = BigDecimal.ZERO;
            for (RespGameOrder gameOrder : result){
                eggAmount = eggAmount.add(new BigDecimal(gameOrder.getAccumulate()).divide(new BigDecimal(10), 2, RoundingMode.HALF_UP));
                payAmount = payAmount.add(new BigDecimal(gameOrder.getPayAmount()));
            }
            seggAmount = seggAmount.add(eggAmount);
            spayAmount = spayAmount.add(payAmount);
        }
        vo.setEggAmount((vo.getEggAmount()==null?BigDecimal.ZERO:vo.getEggAmount()).add(seggAmount));  //鸟蛋抵扣
        vo.setPayAmount((vo.getPayAmount()==null?BigDecimal.ZERO:vo.getPayAmount()).add(spayAmount));  //第三方支付
        logger.warn("赛事：vo=" + JSON.toJSONString(vo));
        return vo;
    }


    private RespClubFinanceReconciliationVo subtractAARefundFee(RespClubFinanceReconciliationVo vo, List<Integer> activityIds){
        if (activityIds == null || activityIds.size() == 0){
            return vo;
        }
        TbAASettlementRefundDetailExample example = new TbAASettlementRefundDetailExample();
        example.createCriteria()
                .andActivityIdIn(activityIds);
        List<TbAASettlementRefundDetail> resultList = aaSettlementRefundDetailMapper.selectByExample(example);
        if (resultList == null || resultList.size() == 0){
            return vo;
        }
        BigDecimal refundEggAmount = BigDecimal.ZERO;
        BigDecimal refundBalanceAmount = BigDecimal.ZERO;
        BigDecimal refundPayAmount = BigDecimal.ZERO;
        for (TbAASettlementRefundDetail detail : resultList){
            BigDecimal ea = new BigDecimal(detail.getRefundAccumulateAmount()).divide(new BigDecimal(10), 2, RoundingMode.HALF_UP); //退鸟蛋
            refundEggAmount = refundEggAmount.add(ea);
            refundBalanceAmount = refundBalanceAmount.add(detail.getRefundBalanceAmount());    //退会费
            refundPayAmount = refundPayAmount.add(detail.getRefundThirdPartyAmount()); //退第三方
        }
        vo.setEggAmount(vo.getEggAmount().subtract(refundEggAmount));
        vo.setBalanceAmount(vo.getBalanceAmount().subtract(refundBalanceAmount));
        vo.setPayAmount(vo.getPayAmount().subtract(refundPayAmount));
        return vo;
    }

    private Date getLastSummaryTime(){
        TbClubFinanceDailyReportExample example = new TbClubFinanceDailyReportExample();
        example.setOrderByClause(" id desc");
        example.setLimit(Limit.buildLimit(0,1));

        List<TbClubFinanceDailyReport> resultList = clubFinanceDailyReportMapper.selectByExample(example);
        if (resultList != null && resultList.size() > 0){
            return resultList.get(0).getCreateTime();
        }
        return new Date();
    }
    /**
     * 获取已经结算的活动
     */
    private Map<Integer, Map<Integer, Date>> queryAlreadySettleActivityIds(List<Integer> clubIds, Date startTime, Date endTime){
        TbClubActivitySettlementExample example = new TbClubActivitySettlementExample();
        TbClubActivitySettlementExample.Criteria criteria = example.createCriteria();
        criteria.andClubIdIn(clubIds);
        if (startTime != null){
            criteria.andCreateTimeGreaterThan(startTime);
        }
        if (endTime != null){
            criteria.andCreateTimeLessThanOrEqualTo(endTime);
        }
        List<TbClubActivitySettlement> settlements = clubActivitySettlementMapper.selectByExample(example);
        Map<Integer, Map<Integer, Date>> clubIdActivityIds = new HashMap<Integer, Map<Integer, Date>>();
        if (settlements != null && settlements.size()>0){
            for (TbClubActivitySettlement settlement : settlements){
                Integer clubIdKey = settlement.getClubId();
                Integer valueActivityId = settlement.getActivityId();
                Date valueActivityUpdateTime = settlement.getUpdateTime();
                if (!clubIdActivityIds.containsKey(clubIdKey)) {
                    Map<Integer, Date> idUpdateTime = new HashMap<Integer, Date>();
                    idUpdateTime.put(valueActivityId, valueActivityUpdateTime);
                    clubIdActivityIds.put(clubIdKey, idUpdateTime);
                } else {
                    Map<Integer, Date> idUpdateTime = clubIdActivityIds.get(clubIdKey);
                    if (idUpdateTime != null) {
                        if (idUpdateTime.containsKey(valueActivityId)) {
                            logger.warn("queryAlreadySettleActivityIds, clubId:{}, DUPLICATE activityId:{}, preUpdateTime:{}, updateTime:{}",clubIdKey,
                                    valueActivityId, idUpdateTime.get(valueActivityId), valueActivityUpdateTime);
                            continue;
                        }
                        idUpdateTime.put(valueActivityId, valueActivityUpdateTime);
                    }
                }
            }
        }

        return clubIdActivityIds;
    }

    /**
     * 获取已经结算的活动
     */
    private List<Integer> queryAlreadySettleActivityIds2(Integer clubId, Date startTime, Date endTime){
        List<Integer> idsAccountStream = new ArrayList<>();
        TbClubOnlineAccountStreamExample exampleAccountStream = new TbClubOnlineAccountStreamExample();
        TbClubOnlineAccountStreamExample.Criteria criteriaAccountStream = exampleAccountStream.createCriteria();
        criteriaAccountStream.andClubIdEqualTo(clubId);
        criteriaAccountStream.andTypeIn(Arrays.asList((byte)1, (byte)2));
        criteriaAccountStream.andStatusEqualTo((byte)1);

        if (startTime != null){
            criteriaAccountStream.andCreateTimeGreaterThan(startTime);
        }
        if (endTime != null){
            criteriaAccountStream.andCreateTimeLessThanOrEqualTo(endTime);
        }
        List<TbClubOnlineAccountStream> settlementsAccountStream =
                clubOnlineAccountStreamMapper.selectByExample(exampleAccountStream);
        if (settlementsAccountStream != null && settlementsAccountStream.size()>0){
            for (TbClubOnlineAccountStream settlement : settlementsAccountStream){
                idsAccountStream.add(settlement.getActivityId());
            }
        }

        return idsAccountStream;
    }

    private RespClubFinanceSummaryVo getSummaryVo(RespClubFinanceSummaryVo summaryVo,Integer cityId, Integer clubId, Date startTime, Date endTime){

        Map<String,Object> map = new HashMap<String,Object>();
        if (null != cityId && 0 != cityId){
            map.put("cityId", cityId);
        }
        if (startTime != null){
            map.put("startTime", startTime);
        }
        if (endTime != null){
            map.put("endTime", endTime);
        }
        TbClubFinanceDailyReportExample reportExample =
                new TbClubFinanceDailyReportExample();
        reportExample.setOrderByClause(" id desc ");
        reportExample.setLimit(Limit.buildLimit(0,1));
        TbClubFinanceDailyReportExample.Criteria criteria =
                reportExample.createCriteria();
        if(null != cityId)
        {
            criteria.andCityIdEqualTo(cityId);
        }
        if(null != startTime && null != endTime)
        {
            criteria.andCreateTimeBetween(startTime, endTime);
        }

        List<TbClubFinanceDailyReport> list =
                clubFinanceDailyReportMapper.selectByExample(reportExample);
        if(!CollectionUtils.isEmpty(list))
        {
            TbClubFinanceDailyReport report = list.get(0);
            summaryVo.setSummaryTime(report.getCreateTime());
        }
        BigDecimal eggAmount = clubFinanceDailyMapper.selectEggAmount(map);
        BigDecimal balanceAmount = clubFinanceDailyMapper.selectBalanceAmount(map);
        BigDecimal payAmount = clubFinanceDailyMapper.selectPayAmount(map);
        BigDecimal withdrawAmount_N_total = clubFinanceDailyMapper.
                selectApplyWithdrawAmount(map);
        BigDecimal withdrawAmount_S_total = clubFinanceDailyMapper.
                selectAlreadyWithdrawAmount(map);

        summaryVo.setBalanceAmountTotal(balanceAmount);
        summaryVo.setEggAmountTotal(eggAmount);
        summaryVo.setPayAmountTotal(payAmount);
        summaryVo.setWithdrawAmount_NTotal(withdrawAmount_N_total);
        summaryVo.setWithdrawAmount_STotal(withdrawAmount_S_total);
        return summaryVo;
    }

    @Override
    public PageObj<List<RespClubPaymentVo>> queryClubPaymentDetailsList(ReqClubPaymentQuery query){

//        TbClubOnlineAccountStreamExample example = new TbClubOnlineAccountStreamExample();
//        TbClubOnlineAccountStreamExample.Criteria criteria = example.createCriteria();

        Map<String, Object> paramMap = new HashMap<>();

        if (query.getClubId() == null){
            return PageObj.create(0, 0, 0, null);
            //throw new BizException("俱乐部ID为空！");
        }
        TbClub tbClub = clubMapper.selectByPrimaryKey(query.getClubId());

//        criteria.andClubIdEqualTo(query.getClubId());
        paramMap.put("clubId", tbClub.getId());

        List<Integer> activityIds = new ArrayList<>();
        Integer activityId = query.getActivityId();
        if (activityId != null && activityId >0){
            //criteria.andActivityIdEqualTo(activityId);
            activityIds.add(activityId);
        } else {
            String activityName = query.getActivityName();
            if (!StringUtil.isBlankOrNull(activityName)){
                List<Integer> activityIdList = activityOpenService.queryActivityIdsByName(activityName);
                if (activityIdList != null && activityIdList.size() > 0) {
                    //criteria.andActivityIdIn(activityIds);
                    activityIds.addAll(activityIdList);
                }else {
                    return PageObj.create(0, 0, 0, null);
                    //throw new BizException("没有查询到此活动！");
                }
            }
        }
        if (activityIds.size() > 0) {
            paramMap.put("activityIds", activityIds);
        }
        String serialNo = query.getSerialNo();
        if (!StringUtil.isBlankOrNull(serialNo)){
            //criteria.andSerialNoEqualTo(serialNo);
            paramMap.put("serialNo", serialNo);
        }
        List<Integer> settleList = new ArrayList<>();
        List<Integer> withdrawList = new ArrayList<>();
        List<Byte> types = query.getTypes();
        if (types != null && types.size() > 0){
            //criteria.andTypeIn(types);
            if (types.contains((byte)1)){
                settleList.add(1);
            }
            if (types.contains((byte)2)){
                settleList.add(2);
            }
            if (types.contains((byte)3)){
                settleList.add(3);
            }
            if (types.contains((byte)0)){
                withdrawList.add(0);
            }
            if (types.contains((byte)-1)){
                withdrawList.add(-1);
            }
        }else {
            settleList.addAll(Arrays.asList(1, 2, 3));  //赛事结算
            withdrawList.addAll(Arrays.asList(-1, 0));  //提现
        }
        if (settleList.size() > 0) {
            paramMap.put("settleList", settleList);
        }
        if (withdrawList.size() > 0) {
            paramMap.put("withdrawList", withdrawList);
        }

        List<Byte> status = query.getStatus();
        if (status != null && status.size() > 0){
            //criteria.andStatusIn(status);
            paramMap.put("status", status);
        }
        Date startTime = getStartTime(query.getStartTime());
        if (startTime != null){
            logger.warn("startTime=" + sf.format(startTime));
            //criteria.andCreateTimeGreaterThanOrEqualTo(startTime);
            paramMap.put("startTime", startTime);
        }
        Date endTime = getEndTime(startTime, query.getEndTime());
        if (endTime != null){
            logger.warn("endTime=" + sf.format(endTime));
            //criteria.andCreateTimeLessThan(endTime);
            paramMap.put("endTime", endTime);
        }
        //example.setOrderByClause(" create_time desc");

        int total = sqlSessionTemplate.selectOne("countClubOnlineAccountStream", paramMap);

        int pageNo = query.getPageNo();
        int pageSize= query.getPageSize();
        paramMap.put("startSize", (pageNo-1)*pageSize);
        paramMap.put("pageSize", pageSize);
//        example.setLimit(Limit.buildLimit(pageNo, pageSize));
//        List<TbClubOnlineAccountStream> resultList = clubOnlineAccountStreamMapper.selectByExample(example);
        List<TbClubOnlineAccountStream> resultList = sqlSessionTemplate.selectList("queryClubOnlineAccountStream", paramMap);

        List<Integer> clubOnlineAccountActivityIds = new ArrayList<>();
        for (TbClubOnlineAccountStream stream : resultList){
            if (stream != null){
                Integer id = stream.getActivityId();
                if (id != null){
                    clubOnlineAccountActivityIds.add(id);
                }
            }
        }
        //Map key: (activity)"id", "name", "fee_type"
        List<Map<String, Object>> activityNameFeeTypeList = new ArrayList<>();
        if (clubOnlineAccountActivityIds.size() > 0) {
            activityNameFeeTypeList = clubActivityMapper.selectActivityNameFeeTypeByIds(clubOnlineAccountActivityIds);
        }
        Map<Integer, Map<String, Object>> activityIdMap = new HashMap<Integer, Map<String, Object>>();
        for(Map<String, Object> activityNameFeeType: activityNameFeeTypeList){
            if(activityNameFeeType.get("id") != null) {
                activityIdMap.put((Integer)activityNameFeeType.get("id"), activityNameFeeType);
            }
        }

        List<RespClubPaymentVo> list = new ArrayList<>();
        for (TbClubOnlineAccountStream stream : resultList){
            if (stream == null){
                continue;
            }
            RespClubPaymentVo vo = new RespClubPaymentVo();
            Integer id = stream.getActivityId();
            if (id != null){
                vo.setActivityId(id);
            }

            vo.setSerialNo(stream.getSerialNo());
            int type = stream.getType();
            int statu = stream.getStatus();

            if (type == -1) {
                vo.setBiz("财务打款");
                vo.setType(1);
                if (statu == 1){
                    vo.setStatus("付款成功");
                }
                if (statu == 2){
                    vo.setStatus("处理中");
                }
                if (statu == 3){
                    vo.setStatus("付款失败");
                }
            }
            if (type == 0){
                vo.setBiz("申请提现");
                vo.setType(2);
                vo.setStatus("待付款");
                TbClubWithdrawalsApplyExample wExample = new TbClubWithdrawalsApplyExample();
                wExample.createCriteria().andApplyNoEqualTo(stream.getSerialNo());
                List<TbClubWithdrawalsApply> withdrawalsApplies = clubWithdrawalsApplyMapper.selectByExample(wExample);
                if (withdrawalsApplies != null && withdrawalsApplies.size()>0) {
                    vo.setIncomeOrPayoutAmount(withdrawalsApplies.get(0).getMoney());
                }
            }
            if (type == 1 || type == 2){
                vo.setType(3);
                vo.setBiz("活动结算");
                vo.setStatus("已结算");

                Map<String, Object> activityNameFeeType = activityIdMap.get(stream.getActivityId());
                if (activityNameFeeType != null) {
                    vo.setActivityName((String)activityNameFeeType.get("name"));
                }
            }
            if (type == 3){
                vo.setType(4);
                vo.setBiz("赛事结算");
                vo.setStatus("已结算");

                List<RespGameOrder> result = stadiumOpenService.queryOrderNoByGameId(id);
                if (result != null && result.size() > 0){
                    BigDecimal eggAmount = BigDecimal.ZERO;
                    BigDecimal payAmount = BigDecimal.ZERO;
                    for (RespGameOrder gameOrder : result){
                        eggAmount = eggAmount.add(new BigDecimal(gameOrder.getAccumulate()).divide(new BigDecimal(10), 2, RoundingMode.HALF_UP));
                        payAmount = payAmount.add(new BigDecimal(gameOrder.getPayAmount()));
                    }
                    vo.setEggAmount(eggAmount);  //鸟蛋抵扣
                    vo.setPayAmount(payAmount);  //第三方支付
                    vo.setActivityName(result.get(0).getGameName());
                }
            }else {
                Integer feeType = null;
                Map<String, Object> activityNameFeeType = activityIdMap.get(stream.getActivityId());
                if (activityNameFeeType != null) {
                    feeType = (Integer)activityNameFeeType.get("fee_type");
                }
                Map<String, List<RespClubOrderDetail>> map = queryActivityOrderListByFeeType(stream.getActivityId(), null, null, feeType);
                BigDecimal duesAmount = BigDecimal.ZERO;
                BigDecimal eggAmount = BigDecimal.ZERO;
                BigDecimal payAmount = BigDecimal.ZERO;
                Set<String> keys = map.keySet();
                for (String key : keys) {
                    List<RespClubOrderDetail> orders = map.get(key);
                    for (RespClubOrderDetail order : orders) {
                        duesAmount = duesAmount.add(order.getBalanceAmount());
                        eggAmount = eggAmount.add(order.getAccumulateAmount());
                        payAmount = payAmount.add(order.getPayAmount());
                    }
                }
                vo.setBalanceAmount(duesAmount); //会费抵扣
                vo.setEggAmount(eggAmount);  //鸟蛋抵扣
                vo.setPayAmount(payAmount);  //第三方支付
            }
            vo.setTime(stream.getCreateTime());
            if (type == -1) {
                vo.setIncomeOrPayoutAmount(stream.getOutputOnline());
            }
            if (type == 1 || type == 2 || type == 3) {
                vo.setIncomeOrPayoutAmount(stream.getIncomeOnline());
            }
            vo.setDuesAmount(stream.getSufAmount()); //余额

            vo.setClubName(tbClub.getClubName());

            list.add(vo);
        }

        return PageObj.create(total, pageNo, pageSize, list);
    }

    /**
     * 导出俱乐部会费线上充值订单列表
     * @param query
     * @return
     */
    @Override
    public List<RespClubRechargeStream> queryClubRechargeStreamReport(ReqClubRechargeQuery query) {
        Map<String ,Object> param = new HashMap<>();
        //俱乐部名称搜索
        String clubName = query.getClubName();
        if (StringUtils.isNotBlank(clubName)) {
            TbClub club = this.getClubByName(query.getClubName());
            if (club != null) {
                param.put("clubId",club.getId());
            }
        }
        //俱乐部ID搜索
        if (query.getClubId() != null && query.getClubId() != 0) {
            param.put("clubId",query.getClubId());
        }
        String mobile = query.getMobile();
        if (StringUtils.isNotBlank(mobile)) {
            RespUserInfoBase response = super.getUserInfoByMobile(mobile);
            if (response != null) {
                param.put("uid", response.getUid());
            }
        }
        String outTradeNo = query.getOutTradeNo();
        if (StringUtils.isNotBlank(outTradeNo)) {
            param.put("outTradeNo",outTradeNo);
        }
        if (query.getStartTime() != null && query.getEndTime() != null) {
            param.put("createTimeStart", DateUtils.dayBegin(query.getStartTime()));
            param.put("createTimeEnd",DateUtils.dayEnd(query.getEndTime()));
        }
        if (query.getPayChannel() != null && query.getPayChannel() != 0) {
            param.put("payChannel",query.getPayChannel());
        }
        if (query.getStatusList() != null && !query.getStatusList().isEmpty()) {
            param.put("statusList",query.getStatusList());
        }
        List<RespClubRechargeStream> streams = this.clubAccountExtendMapper.getClubOnlineMemberRechargeStream(param);
        List<Integer> uids = new ArrayList<>();
        for (RespClubRechargeStream stream : streams) {
            uids.add(stream.getUid());
        }
        Map<Integer,RespUserInfoBase> userInfoBaseMap = userServiceFacade.batchQueryUserInfoToMap(uids);
        for (RespClubRechargeStream stream : streams) {
            if (userInfoBaseMap == null) {
                stream.setNickName("");
                stream.setMobile("");
            } else {
                RespUserInfoBase respUserInfoBase = userInfoBaseMap.get(stream.getUid());
                if (respUserInfoBase != null) {
                    stream.setNickName(respUserInfoBase.getNickName());
                    stream.setMobile(respUserInfoBase.getMobile());
                } else {
                    stream.setNickName("");
                    stream.setMobile("");
                }
            }
        }
        return streams;
    }

    @Override
    public Map<String, List<RespClubOrderDetail>> queryActivityOrderList(Integer activityId,Integer pageNo,Integer pageSize) {
        Map<String, List<RespClubOrderDetail>> resultMap = new TreeMap<>();
        if (activityId == null) {
            return resultMap;
        }

        TbOrderExample example = new TbOrderExample();
        example.createCriteria()
                .andActivityIdEqualTo(activityId)
                .andOrderStatusIn(Arrays.asList((byte)2,(byte)6, (byte)7, (byte)9)); //2支付成功的，7已评价的， 6AA退款成功, 9交易成功但结算失败

        example.setOrderByClause(" order_no asc");
        if(pageNo != null && pageSize != null){
            example.setLimit(Limit.buildLimit(pageNo, pageSize));
        }

        int total = orderMapper.countByExample(example);
        List<TbOrder> orderList = orderMapper.selectByExample(example);

        for (TbOrder order : orderList){
            String orderNo = order.getOrderNo();
            List<RespClubOrderDetail> orderDetailsList = new ArrayList<>();
            RespClubOrderDetail o = new RespClubOrderDetail();                           //订单本身的记录
            o.setOrderNo(orderNo);
            o.setOrderAmount(order.getOrderAmount());
            o.setPayAmount(order.getPayAmount());
            o.setBalanceAmount(order.getBalanceAmount());
            o.setAccumulateAmount(order.getExchangeRmb());
            o.setPayType((int)order.getPayType());
            o.setTradeNo(getRefundTradeNo(o.getOrderNo(), true));
            o.setTotal(total);
            byte orderStatus = order.getOrderStatus();
            if (orderStatus == 2 || orderStatus == 6 || orderStatus == 7){
                o.setStatus("已到账");
                o.setStatusCode(0);
            } else if (orderStatus == 9) {
                o.setStatus("结算失败");
                o.setStatusCode(4);
            } else {
                o.setStatus(String.valueOf(orderStatus));
            }
            o.setTime(order.getCreateTime());
            orderDetailsList.add(o);
            List<RespClubOrderDetail> orderRefundList = queryRefundOrderList(orderNo);  //去AA退款流水表查询是否有退款记录
            orderDetailsList.addAll(orderRefundList);
            if (!resultMap.containsKey(order.getOrderNo())){
                resultMap.put(order.getOrderNo(), orderDetailsList);
            }else {
                List<RespClubOrderDetail> value = resultMap.get(order.getOrderNo());
                value.addAll(orderDetailsList);
                resultMap.put(order.getOrderNo(), value);
            }
        }
        return resultMap;
    }


    //不修改现有接口, 有其他地方调用, 增加一个新接口
    private Map<String, List<RespClubOrderDetail>> queryActivityOrderListByFeeType(Integer activityId,Integer pageNo,Integer pageSize, Integer feeType) {
        Map<String, List<RespClubOrderDetail>> resultMap = new TreeMap<>();
        if (activityId == null) {
            return resultMap;
        }

        TbOrderExample example = new TbOrderExample();
        example.createCriteria()
                .andActivityIdEqualTo(activityId)
                .andOrderStatusIn(Arrays.asList((byte)2,(byte)6, (byte)7)); //2支付成功的，7已评价的， 6AA退款成功

        example.setOrderByClause(" order_no asc");
        if(pageNo != null && pageSize != null){
            example.setLimit(Limit.buildLimit(pageNo, pageSize));
        }

        int total = orderMapper.countByExample(example);
        List<TbOrder> orderList = orderMapper.selectByExample(example);

        for (TbOrder order : orderList){
            String orderNo = order.getOrderNo();
            List<RespClubOrderDetail> orderDetailsList = new ArrayList<>();
            RespClubOrderDetail o = new RespClubOrderDetail();                           //订单本身的记录
            o.setOrderNo(orderNo);
            o.setOrderAmount(order.getOrderAmount());
            o.setPayAmount(order.getPayAmount());
            o.setBalanceAmount(order.getBalanceAmount());
            o.setAccumulateAmount(order.getExchangeRmb());
            o.setPayType((int)order.getPayType());
            o.setTradeNo(getRefundTradeNo(o.getOrderNo(), true));
            o.setTotal(total);
            byte orderStatus = order.getOrderStatus();
            if (orderStatus == 2 || orderStatus == 6 || orderStatus == 7){
                o.setStatus("已到账");
                o.setStatusCode(0);
            }else {
                o.setStatus(String.valueOf(orderStatus));
            }
            o.setTime(order.getCreateTime());
            orderDetailsList.add(o);
            if (feeType == null || feeType != 1) {
                List<RespClubOrderDetail> orderRefundList = queryRefundOrderList(orderNo);  //去AA退款流水表查询是否有退款记录
                orderDetailsList.addAll(orderRefundList);
            }
            if (!resultMap.containsKey(order.getOrderNo())){
                resultMap.put(order.getOrderNo(), orderDetailsList);
            }else {
                List<RespClubOrderDetail> value = resultMap.get(order.getOrderNo());
                value.addAll(orderDetailsList);
                resultMap.put(order.getOrderNo(), value);
            }
        }
        return resultMap;
    }

    private String getRefundTradeNo(String orderNo, boolean pay){
        ReqOrderInfo reqOrderInfo = new ReqOrderInfo();
        reqOrderInfo.setOutTradeNo(orderNo);
        APIRequest<ReqOrderInfo> request = new APIRequest<>();
        request.setData(reqOrderInfo);
        APIResponse<RespOrderInfo> respons = orderPayService.orderQuery(request);
        if (respons != null && respons.isRet() && respons.getData() != null){
           if (pay){
               return respons.getData().getPayTsn();
           }else {
               List<RefundNotifyMsg> list = respons.getData().getRefundList();
               if (list != null && list.size() > 0) {
                   return list.get(0).getTsnRefundNo();
               }
           }
        }
        return "";
    }

    /**
     * 查询AA退款订单
     */
    private List<RespClubOrderDetail> queryRefundOrderList(String orderNo){

        List<RespClubOrderDetail> result = new ArrayList<>();

        TbAASettlementRefundDetailExample aaExample = new TbAASettlementRefundDetailExample();
        aaExample.createCriteria()
                .andOrderNoEqualTo(orderNo)
                .andRefundStatusEqualTo((byte)2);//退款成功
        List<TbAASettlementRefundDetail> list = aaSettlementRefundDetailMapper.selectByExample(aaExample);
        for (TbAASettlementRefundDetail detail : list){
            RespClubOrderDetail o = new RespClubOrderDetail();
            o.setOrderNo(orderNo);
            o.setTradeNo(getRefundTradeNo(o.getOrderNo(), false));
            BigDecimal balanceAmount = detail.getRefundBalanceAmount().multiply(new BigDecimal(-1));
            o.setBalanceAmount(balanceAmount);
            BigDecimal payAmount = detail.getRefundThirdPartyAmount().multiply(new BigDecimal(-1));
            o.setPayAmount(payAmount);
            BigDecimal accumulateAmount = new BigDecimal(detail.getRefundAccumulateAmount()).divide(new BigDecimal(10), 2, RoundingMode.HALF_UP).multiply(new BigDecimal(-1));
            o.setAccumulateAmount(accumulateAmount);
            o.setPayType((int)detail.getPayId());
            o.setTime(detail.getCreateTime());

            BigDecimal orderAmount = BigDecimal.ZERO;
            orderAmount = orderAmount.add(payAmount).add(balanceAmount).add(accumulateAmount);
            o.setOrderAmount(orderAmount);

            Byte refund_status = detail.getRefundStatus();
            if (refund_status == 1) {
                o.setStatus("退款中");
                o.setStatusCode(1);
            }
            if (refund_status == 2){
                o.setStatus("退款成功");
                o.setStatusCode(2);
            }
            if (refund_status == 3){
                o.setStatus("退款失败");
                o.setStatusCode(3);
            }
            result.add(o);
        }

        return result;
    }
}
